package com.itheima.controller.admin;


import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/report")
@Api(tags = "统计")
public class ReportController {
    @Autowired
    private ReportService reportService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private SetmealService setmealService;

    @GetMapping("/getMemberReport")
    @ApiOperation("会员数量统计")
    public Result getMemberReport() {
        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();
        Calendar calendar = Calendar.getInstance(); //  创建日历对象
        calendar.add(Calendar.MONTH, -12);//  获取当前时间减去12个月
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);//  获取当前时间加一个月
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy-MM").format(date));//  格式化时间
        }
        map.put("months", months);
        List<Integer> memberCount = memberService.findMemberCountByMonths(months);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    @GetMapping("/getSetmealReport")
    @ApiOperation("套餐占比统计")
    public Result getSetmealReport() {
        Map<String, Object> data = new HashMap<>();

        List<Map<String, Object>> setmealCount = setmealService.findSetmealCount();
        data.put("setmealCount", setmealCount);

        List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : setmealCount) {
            setmealNames.add(stringObjectMap.get("name").toString());
        }
        data.put("setmealNames", setmealNames);

        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);

    }

    /**
     * 获取运营统计数据
     */
    @GetMapping("/getBusinessReportData")
    @ApiOperation("获取运营统计数据")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> result = reportService.getBusinessReport();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /*导出运营数据到Excel文件*/

    @GetMapping("/exportBusinessReport")
    @ApiOperation("导出运营数据到Excel文件")
    public Result exportBusinessReport(HttpServletResponse response) {

        try {
            Map<String, Object> result = reportService.getBusinessReport();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //创建Excel文件
            FileInputStream input = new FileInputStream(new File("D:\\templates\\report_template.xlsx"));
            //读取磁盘上已经存在的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(input);
            //读取第一个表
            XSSFSheet sheet = excel.getSheetAt(0);
            //获得第三行
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期


            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数
            row.getCell(7).setCellValue(totalMember);//总会员数
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for (Map map : hotSetmeal) {// 热门套餐
                String name = (String) map.get("name");//套餐名称
                Long setmealCount = (Long) map.get("setmeal_count");//预约数量
                BigDecimal proportion = (BigDecimal) map.get("proportion");//占比
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmealCount);
                row.getCell(6).setCellValue(proportion.doubleValue());
            }

            //使用输出流将文件下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//  Excel文件类型
            response.setHeader("Content-Disposition", "attachment;filename=report.xlsx");//文件名称report.xlsx

            excel.write(out);
            out.flush();
            out.close();
            excel.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }

    }

}
